from logzero import logger
from django.views.decorators.csrf import csrf_exempt


from service.models import Administrator
import django.utils.timezone as timezone

from .models import log

OperateType = {"add": 1, "update": 2, "delete": 3, "backup": 4, "rollback": 5}

class operatorLog:
    def __init__(self):
        sql = Administrator(Name='admin', Account='admin', Psw='admin')
        sql.save()

    def __insert(self, request, type, details, project):
        userAccount = request.session['account']
        logger.info("operator log : user_account :[%s] , operate_type : [%s] ,"
                    " operate_details : [%s] ,operate_time : [%s], operate_project : [%s]"
                    , userAccount, type, details, timezone.now(), project)
        logInfo = log(operator=userAccount, operationType=type, project=project, detail=details)
        try:
            logInfo.save()
        except:
            logger.exception("insert operate log exception")

    def select_log_filter_by_type(self, type):
        return log.objects.filter(operate_type=type)

    def select_all_log(self):
        return log.objects.all()

    def add(self, request, details, project):
        self.__insert(request, OperateType["add"], details, project)

    def update(self, request, details, project):
        self.__insert(request, OperateType["update"], details, project)

    def delete(self, request, details, project):
        self.__insert(request, OperateType["delete"], details, project)

    def backup(self, request, details, project):
        self.__insert(request, OperateType["backup"], details, project)

    def rollback(self, request, details, project):
        self.__insert(request, OperateType["rollback"], details, project)

operate_log = operatorLog()
